/**
 * handle web-socket connection.
 */
var users = require("../User/users.js");
var toekverifier = require("../token/gentok.js");

function accept(tk, ws) {
	"use strict";
	if (users[tk.account]) {
		ws.close();
		return;
	}
	var account = tk.account;
	
	var user = {};
	user.account = account;
	user.ws = ws;
	users.addNew(user);
	
	// because the web-socket should only use to send notification
	// so it should not receive any message.
	ws.on("message", function(msg, flags) {
		console.log("this websocket should not received msg");
		ws.close();
		users.del(account);
	});
	
	ws.on("close", function(code, msg){
		console.log("websocket close, code:" + code + ",msg:" + msg);
		users.del(account);
	});
}

function usher(ws) {
	"use strict";
	ws.on("message", function(msg, flags) {
		clearTimeout(ws.usherTID);
		
		var needClose = true;
		if (flags.binary) {
			console.error("this websocket can only support text message");
		} else {
			var msg2 = JSON.parse(msg);
			if (msg2.token) {
				var tk = toekverifier.parse(msg2.token);
				if (tk !== null && !tk.isExpired) {
					accept(tk, ws);
					needClose = false;
				}
			}
		}
		
		if (needClose) {
			ws.close();
		}
	});

	function timeout() {
		ws.close();
	}

	ws.usherTID = setTimeout(timeout, 3 * 1000);
}

function wsConnectHandler(wscoket) {
	"use strict";
	usher(wscoket);
}

module.exports = wsConnectHandler;
